<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开 -->
        <el-table-column type="expand">
          <template slot-scope="scpoe">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '']" v-for="(item1, i1) in scpoe.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightId(scpoe.row, item1.id)"> {{ item1.authName }}</el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级 -->
              <el-col :span="19">
                <!-- 通过for渲染二级 -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightId(scpoe.row, item2.id)">{{ item2.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightId(scpoe.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scpoe.row }}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- <input type="hidden" :value="scope.row" /> -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoleInfo(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleInfo(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addROleVisible" width="50%" @close="addRoleClose">
      <!-- 主体 -->
      <el-form :model="addForm" ref="addFormRef" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addROleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addROle">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色 -->
    <!-- 修改用户 -->
    <el-dialog title="修改角色" :visible.sync="editRoleVisible" width="50%">
      <!-- 主体 -->
      <el-form :model="editForm" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="ediRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
      <!-- 树形空间 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" :default-checked-keys="defKeys" default-expand-all ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRolesList, delRightById, getRights, setRoleRights, addRole, editRole, delRole } from '@/api'
export default {
  name: 'rolesList',
  data() {
    return {
      // 所有角色列表数据
      roleList: [],
      // 分配权限对话框
      setRightDialogVisible: false,
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },

      // 默认选中节点id值
      defKeys: [],
      // 角色id
      roleId: '',
      // 添加角色弹出框
      addROleVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },

      // 修改用户弹出框
      editRoleVisible: false,
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      editFormId: ''
    }
  },
  methods: {
    // 递归获取三级id
    getRoles(node, arr) {
      // 如果node节点不包含children属性，则为三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getRoles(item, arr)
      })
    },
    // 根据id删除权限
    async removeRightId(role, rightId) {
      const ress = await this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (ress !== 'confirm') return ''
      const { data: res } = await delRightById(role.id, rightId)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      console.log(res)
      role.children = res.data
      this.$message.success('删除权限成功')
    },
    // 展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await getRights()
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败！')
      // console.log(res)
      this.rightsList = res.data
      console.log(this.rightsList)
      this.getRoles(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 监听分配权限对话框的关闭事件
    setRightsClosed() {
      this.defKeys = []
    },
    // 为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await setRoleRights(this.roleId, idStr)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.getRolesLists()
      this.$message.success('分配用户权限成功')
      this.setRightDialogVisible = false
    },
    // 获取角色列表
    async getRolesLists() {
      const { data: res } = await getRolesList()
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      console.log(res)
      this.roleList = res.data
    },
    // 添加角色点击事件
    addRoles() {
      this.addROleVisible = true
    },
    // 添加角色确定事件
    async addROle() {
      if (!this.addForm.roleName) return this.$message.warning('角色名称不能为空')
      const { data: res } = await addRole(this.addForm)
      if (res.meta.status !== 201) return this.$message.error('获取角色数据失败')
      this.$message.success('添加角色成功')
      this.getRolesLists()
      this.addROleVisible = false
    },
    // 添加角色弹窗关闭
    addRoleClose() {
      this.addForm = {}
    },
    // 修改角色点击事件
    editRoleInfo(val) {
      console.log(val)
      this.editFormId = val.id
      this.editForm.roleName = val.roleName
      this.editForm.roleDesc = val.roleDesc
      this.editRoleVisible = true
    },
    // 修改角色确定事件
    async ediRole() {
      // console.log(id)
      if (!this.editForm.roleName) return this.$message.warning('角色名称不能为空')
      const { data: res } = await editRole(this.editFormId, this.editForm)
      if (res.meta.status !== 200) return this.$message.error('修改角色失败')
      this.$message.success('修改角色成功')
      this.getRolesLists()
      this.editRoleVisible = false
    },
    // 删除角色事件
    async removeRoleInfo(id) {
      const ress = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (ress === 'confirm') {
        const { data: res } = await delRole(id)
        if (res.meta.status !== 200) return this.$message.error('删除角色失败')
        this.$message.success('删除成功')
        this.getRolesLists()
      }
    }
  },
  created() {
    this.getRolesLists()
  }
}
</script>

<style lang="less" scoped>
.el-row {
  display: flex;
  align-items: center;
  justify-content: center;
  .el-col-5 {
    position: relative;
    left: 3%;
  }
}
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
